<template>
  <div class="addArticle">
    <el-card>
      <my-header :title="varTitle" slot="header"></my-header>
      <!-- 主体 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item prop="title" label="标题">
          <el-input :maxlength="30" v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item prop="content" label="内容">
          <quillEditor
            v-model="form.content"
            @change="editorChange"
            :options="editorOptions"
          ></quillEditor>
        </el-form-item>
        <el-form-item label="封面">
          <el-radio-group v-model="form.cover.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <div
            class="cover"
            v-show="form.cover.type === 1 || form.cover.type === 3"
          >
            <img
              @click="isShowDialog(index)"
              v-for="(item, index) in form.cover.images"
              :src="item || imgSrc"
              :key="index"
            />
          </div>
        </el-form-item>
        <el-form-item label="频道" prop="channel_id">
          <el-select v-model="form.channel_id">
            <el-option
              v-for="item in channel_ids"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.stop="submit">{{
            sendOrsave
          }}</el-button>
          <el-button @click.stop="caogao" v-if="$route.query.id === undefined"
            >存入草稿</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <myDialog
      ref="myDialog"
      :imgIndex="imgIndex"
      @confirmImg="confirmImg"
    ></myDialog>
  </div>
</template>
<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import {
  getChannels,
  publication,
  getArticleById,
  setArticle
} from '@/api/articles'
import myDialog from '@/components/myDialog'
import imgSrc from '../../assets/pic_bg.png'
export default {
  name: 'addArticle',
  components: { quillEditor, myDialog },
  watch: {
    'form.cover.type' (newValue) {
      this.$refs.myDialog.imageUrl = ''
      if (newValue === 1) {
        this.form.cover.images.length = 1
      } else if (newValue === 3) {
        this.form.cover.images.length = 3
      }
    },
    '$route.query.id' (val) {
      if (val) {
        this.varTitle = '编辑文章'
      } else {
        this.sendOrsave = '发表'
        this.varTitle = '发布文章'
        this.form = {
          title: '',
          content: '',
          cover: {
            type: 0,
            images: []
          },
          channel_id: ''
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    }
  },
  data () {
    return {
      sendOrsave: '',
      varTitle: '',
      // 选中的图片
      imgIndex: -1,

      // 频道id
      channel_ids: [],
      // 默认图片
      imgSrc: imgSrc,
      form: {
        title: '',
        content: '',
        cover: {
          type: 0,
          images: []
        },
        channel_id: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trgger: 'change' },
          { min: 5, max: 30, message: '请输入5-30个字符', trgger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trgger: 'change' }
        ],
        channel_id: [
          {
            validator (rule, value, callback) {
              if (value !== '') {
                callback()
              } else {
                callback(new Error('请选择频道'))
              }
            }
          }
        ]
      },
      // 编辑器配置项
      editorOptions: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'link', 'underline'],
            [{ header: 1 }, { header: 2 }],
            [{ indent: '-1' }, { indent: '+1' }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote', 'code-block'],
            ['image'] // toggled buttons
          ]
        },
        placeholder: '请在这里输入...'
      }
    }
  },
  methods: {
    caogao () {
      this.$refs.form.validate(result => {
        if (result) {
          publication({ draft: true }, this.form)
            .then(res => {
              this.$message.success('发布成功!')
              this.form.cover.images.splice(0)
              this.$refs.form.resetFields()
              this.$nextTick(() => {
                this.$refs.form.clearValidate()
              })
            })
            .catch(err => {
              this.$message.error(err)
            })
        }
      })
    },
    // 提交发布接口
    submit () {
      this.$refs.form.validate(result => {
        if (result) {
          if (this.$route.query.id) {
            // 编辑
            if (this.form.cover.type === 0) {
              this.form.cover.images.splice(0)
            } else if (this.form.cover.type === 3) {
              if (this.form.cover.images.includes(undefined)) {
                this.$message.warning('请选择三张图片')
                return
              }
            }
            this.$nextTick(() => {
              setArticle(this.$route.query.id, this.form)
                .then(() => {
                  this.$message.success('保存成功')
                  this.$router.push('/articles')
                })
                .catch(() => {
                  this.$message.error('有误,请重试')
                })
            })
          } else {
            //  发布
            if (this.form.cover.type === 0) {
              this.form.cover.images.splice(0)
            } else if (this.form.cover.type === 3) {
              if (this.form.cover.images.includes(undefined)) {
                this.$message.warning('请选择三张图片')
                return
              }
            }
            this.$nextTick(() => {
              publication({ draft: false }, this.form)
                .then(res => {
                  this.$message.success('发布成功!')
                  this.form = {
                    title: '',
                    content: '',
                    cover: {
                      type: 0,
                      images: []
                    },
                    channel_id: ''
                  }
                  this.$nextTick(() => {
                    this.$refs.form.clearValidate()
                  })
                })
                .catch(() => {
                  this.$message.error('错误,请重试')
                })
            })
          }
        }
      })
    },
    // 点击图片事件
    isShowDialog (index) {
      this.imgIndex = index
      this.$refs.myDialog.ShowDialog = true
    },
    // 点击确定更改预览图
    confirmImg (url, index) {
      if (this.form.cover.type === 1) {
        this.form.cover.images.shift()
        this.form.cover.images.push(url)
      } else if (this.form.cover.type === 3) {
        this.$set(this.form.cover.images, index, url)
      }
    },

    // 富文本编辑器值改变事件
    editorChange (value) {
      this.$refs.form.validateField(['content'], () => {})
    }
  },
  async created () {
    const id = this.$route.query.id
    if (id) {
      this.sendOrsave = '保存'
      this.varTitle = '编辑文章'
      // 请求接口
      const res = await getArticleById(id)
      delete res.data.id
      this.form = res.data
    } else {
      this.sendOrsave = '发表'
      this.varTitle = '发布文章'
    }
    const res = await getChannels()
    this.channel_ids = res.data.channels
  }
}
</script>
<style lang="less">
.addArticle {
  .ql-editor {
    height: 300px;
  }
  .cover {
    display: flex;
    img {
      cursor: pointer;
      border: 1px dashed #ccc;
      margin-right: 40px;
      width: 150px;
      height: 150px;
      display: block;
    }
  }
}
</style>
